package com.daisuxia.web.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.service.RepaymentService;

import net.sf.json.JSONObject;

public class P2pUtils {

	private static Logger loger = Logger.getLogger(RepaymentService.class);
	/**
	 * 还款成功通知p2p订单结束
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static  Map<String,Object> finishOrder(String userApplyNo,Long timestamp){
		LinkedHashMap<String, String> mapApi = SysCacheUtils.getConfigParams(BackConfigParams.YANGYUE_MDL_API);
		String url = mapApi.get(BackConfigParams.MDL_FINISH_ORDER_URL);
		//String url = "http://pcontoso.com/pay/user_apply_no_callback";
		String key = mapApi.get(BackConfigParams.MDL_SYS_KEY);
		//String key ="p2psecert123";
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("user_apply_no", userApplyNo);
		param.put("time", timestamp.toString());
		String pxh = MapConvertCoreUtils.createLinkString(MapConvertCoreUtils.paraFilter(param));
		String sign = PMD5Utils.encodeByMD5( key + "|" + pxh);
		param.put("sign", sign);
		Map<String, String> w = MapConvertCoreUtils.object2MapString(param);
		Map<String,Object> result = new HashMap<String,Object>();

			loger.info("请求p2p结束订单参数：:"+w);
			//如果p2p返回不正确则最多调3次
			int callCount = 0;
			do {
				String res="";
				try {
					res = WebClient.getInstance().doPost(url, w);
					loger.info("请求p2p结束订单返回结果：:"+res);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(StringUtils.isNotBlank(res)) {
					JSONObject json = JSONObject.fromObject(res);
					result = JSONObject.fromObject(json);
				}
				 callCount++;
			}while((null==result || !"success".equals(result.get("status"))&&callCount<=3));
	
		return result;
	}
	public static void main(String[] args) {
		 //Map<String,Object> result = finishOrder("6319188849453305856",System.currentTimeMillis());
	}
}
